package com.pengchuang.ACS.face.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.pengchuang.ACS.admin.api.feign.UserFeignClient;
import com.pengchuang.ACS.common.constant.GlobalConstants;
import com.pengchuang.ACS.common.entity.UserEntity;
import com.pengchuang.ACS.common.utils.*;
import com.pengchuang.ACS.face.dao.FileDao;
import com.pengchuang.ACS.face.dao.RecordDao;
import com.pengchuang.ACS.face.entity.FileEntity;
import com.pengchuang.ACS.face.entity.RecordEntity;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.pengchuang.ACS.face.dao.DoorDao;
import com.pengchuang.ACS.face.entity.DoorEntity;
import com.pengchuang.ACS.face.service.DoorService;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Log4j
@Service("doorService")
public class DoorServiceImpl extends ServiceImpl<DoorDao, DoorEntity> implements DoorService {

    @Autowired
    public DoorDao doorDao;

    @Autowired
    public FileDao fileDao;
    
    @Autowired
    public UserFeignClient userFeignClient;
    
    @Autowired
    public RecordDao recordDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        Object role = request.getAttribute("role");
        QueryWrapper<DoorEntity> queryWrapper = new QueryWrapper<DoorEntity>();
        if ("admin".equals(role)) {
            // 查看用户权限
            queryWrapper.eq("cell_id", request.getAttribute("cellId"));
            queryWrapper.like("door_name", params.get("doorName"));
        } else {
            queryWrapper.like("cell_name", params.get("cellName"));
        }
        IPage<DoorEntity> page = this.page(
                new Query<DoorEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 验证验证码
     * @param code
     * @return
     */
    @Override
    public R validCode(String code) {
        DoorEntity doorEntity = this.baseMapper.selectOne(new QueryWrapper<DoorEntity>().eq("auth_code", code));
        if (doorEntity == null) {
            return R.error(ResultCode.DOOR_ERROR);
        }
        return R.ok();
    }


    /**
     * 验证人脸过程
     * @param files
     * @return
     */
    @Override
    public R validFace(String files, String code) {
        Boolean flag = true;
        DoorEntity doorEntity = doorDao.selectOne(new QueryWrapper<DoorEntity>().eq("auth_code", code));
        // 不存在该门禁密钥
        if (doorEntity == null) {
            return R.error();
        }
        Map<String, Object> param = new HashMap<>();
        param.put("filename", files);
        // 进行人脸微服务请求操作
        String post = HttpRequest.get(GlobalConstants.FACE_URL_PATH + "face_detect")
                .form(param)//表单内容
                .timeout(2000)//超时，毫秒
                .execute().body();

        Map<String, Object> result = JSON.parseObject(post);
        Map<String, Object> result1 = null;
        Long userId = null;
        if (result.containsKey("result")) {
            result = JSON.parseObject(String.valueOf(result.get("result")));
            userId = Long.parseLong(String.valueOf(result.get("userId")));
            Double grade = Double.parseDouble(String.valueOf(result.get("grade")));
            if (grade >= 80.0) {
                // 判断不通过，进行拒绝
                flag = false;
            }
            result1 = new HashMap<>();
            result1.put("result", result);
        }


        // 进行门禁记录操作 TODO
        log.info("{}人脸信息记录 : " + post);
        // 文件记录操作
        FileEntity file = FileEntity.builder()
                .fileName(files)
                .filePath(GlobalConstants.TEMP_FILEPATH + files)
                .fileType("jpg")
                .status(1)
                .userId(Long.parseLong(String.valueOf(result1.get("userId")))).build();
        fileDao.insert(file);

        // 记录插入操作
        // 查询用户
        R userInfoByUserId = userFeignClient.getUserInfoByUserId(userId);
        UserEntity userEntity = JSON.parseObject(String.valueOf(userInfoByUserId.get("result")), UserEntity.class);
        RecordEntity recordEntity = RecordEntity.builder()
                .fileId(file.getId())
                .fileUrl(file.getFilePath())
                .cellId(doorEntity.getCellId())
                .cellName(doorEntity.getCellName())
                .doorId(doorEntity.getId())
                .doorName(doorEntity.getDoorName())
                .uid(userId)
                .nickname(userEntity.getNickname())
                .username(userEntity.getUsername())
                .type(1) // 用标记1表示人脸识别数据
                .build();

        if (flag) recordEntity.setStatus(1);
        recordDao.insert(recordEntity);
        
        if (!flag)
            return R.error(ResultCode.DOOR_ERROR);
        return R.ok(result1);
    }

}